package enhance.plus.config;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import common.core.util.CustomizeRuntimeException;
import enhance.plus.handler.LogicMetaObjectHandler;
import enhance.plus.handler.LogicMetaObjectHandlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liubo
 * @created 2020-07-17 15:50
 */
@Configuration
public class DatabaseConfig {
    @Bean
    public IdentifierGenerator idGenerator() {
        return new IdentifierGenerator() {
            @Override
            public Number nextId(Object entity) {
                throw new CustomizeRuntimeException("ID 生成异常");
            }

            @Override
            public String nextUUID(Object entity) {
                return IdWorker.get32UUID();
            }
        };
    }

    @Autowired
    private LogicMetaObjectHandlerService logicMetaObjectHandlerService;

    @Bean
    @ConditionalOnMissingBean(LogicMetaObjectHandlerService.class)
    public LogicMetaObjectHandlerService logicMetaObjectHandlerService(){
        return new LogicMetaObjectHandlerService(){};
    }

    @Bean
    public LogicMetaObjectHandler logicMetaObjectHandler(){
        return new LogicMetaObjectHandler(logicMetaObjectHandlerService);
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}